import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:flutter/foundation.dart';

import '../../../core/base/base_service.dart';

/// 本地存储服务
/// 使用GetStorage提供本地存储功能
class LocalStorageService extends GetxService {
  late final GetStorage _box;
  
  // 存储盒名称
  static const String boxName = 'hiot_app_box';
  
  @override
  void onInit() {
    super.onInit();
    _box = GetStorage(boxName);
  }
  
  /// 写入数据
  Future<void> write(String key, dynamic value) async {
    await _box.write(key, value);
  }
  
  /// 读取数据
  T? read<T>(String key) {
    return _box.read<T>(key);
  }
  
  /// 移除数据
  Future<void> remove(String key) async {
    await _box.remove(key);
  }
  
  /// 清空所有数据
  Future<void> erase() async {
    await _box.erase();
  }
  
  /// 检查键是否存在
  bool hasData(String key) {
    return _box.hasData(key);
  }
  
  /// 监听键变化
  void listenKey(String key, Function(dynamic) callback) {
    _box.listenKey(key, callback);
  }
  
  /// 获取所有数据
  Map<String, dynamic> getValues() {
    return _box.getValues();
  }
  
  /// 获取所有键
  List<String> getKeys() {
    return _box.getKeys<String>().toList();
  }
  
  /// 写入对象
  Future<void> writeObject<T>(String key, T object) async {
    if (object is Map || object is List) {
      return await _box.write(key, object);
    } else {
      try {
        final map = jsonDecode(jsonEncode(object));
        return await _box.write(key, map);
      } catch (e) {
        debugPrint('无法序列化对象: $e');
        throw Exception('无法序列化对象: $e');
      }
    }
  }
  
  /// 读取对象
  T? readObject<T>(String key, T Function(Map<String, dynamic> json) fromJson) {
    try {
      final value = _box.read(key);
      if (value == null) return null;
      
      if (value is Map<String, dynamic>) {
        return fromJson(value);
      } else {
        return null;
      }
    } catch (e) {
      debugPrint('读取对象出错: $e');
      return null;
    }
  }
  
  /// 读取对象列表
  List<T>? readObjectList<T>(
    String key,
    T Function(Map<String, dynamic> json) fromJson,
  ) {
    try {
      final value = _box.read(key);
      if (value == null) return null;
      
      if (value is List) {
        return value
            .map((item) => fromJson(item as Map<String, dynamic>))
            .toList();
      } else {
        return null;
      }
    } catch (e) {
      debugPrint('读取对象列表出错: $e');
      return null;
    }
  }
  
  /// 设置过期时间
  Future<void> setExpiry(String key, Duration duration) async {
    final expiryKey = '${key}_expiry';
    final expiry = DateTime.now().add(duration);
    await _box.write(expiryKey, expiry.toIso8601String());
  }
  
  /// 获取过期时间
  DateTime? getExpiry(String key) {
    final expiryKey = '${key}_expiry';
    final expiry = _box.read<String>(expiryKey);
    if (expiry == null) return null;
    
    try {
      return DateTime.parse(expiry);
    } catch (e) {
      debugPrint('解析过期时间出错: $e');
      return null;
    }
  }
  
  /// 检查是否已过期
  bool isExpired(String key) {
    final expiry = getExpiry(key);
    if (expiry == null) return false;
    
    return DateTime.now().isAfter(expiry);
  }
}

/// 本地存储服务
class LocalStorageServiceOld {
  /// 存储实例
  final GetStorage _storage;
  
  /// 存储键名
  static const _keys = _StorageKeys();

  /// 构造函数
  LocalStorageServiceOld() : _storage = GetStorage();

  /// 初始化存储
  static Future<void> init() async {
    await GetStorage.init();
  }

  /// 保存令牌
  Future<void> saveToken(String token) async {
    try {
      await _storage.write(_keys.token, token);
    } catch (e) {
      debugPrint('保存令牌错误: $e');
    }
  }

  /// 获取令牌
  Future<String?> getToken() async {
    try {
      return _storage.read<String>(_keys.token);
    } catch (e) {
      debugPrint('获取令牌错误: $e');
      return null;
    }
  }

  /// 移除令牌
  Future<void> removeToken() async {
    try {
      await _storage.remove(_keys.token);
    } catch (e) {
      debugPrint('移除令牌错误: $e');
    }
  }

  /// 保存刷新令牌
  Future<void> saveRefreshToken(String refreshToken) async {
    try {
      await _storage.write(_keys.refreshToken, refreshToken);
    } catch (e) {
      debugPrint('保存刷新令牌错误: $e');
    }
  }

  /// 获取刷新令牌
  Future<String?> getRefreshToken() async {
    try {
      return _storage.read<String>(_keys.refreshToken);
    } catch (e) {
      debugPrint('获取刷新令牌错误: $e');
      return null;
    }
  }

  /// 移除刷新令牌
  Future<void> removeRefreshToken() async {
    try {
      await _storage.remove(_keys.refreshToken);
    } catch (e) {
      debugPrint('移除刷新令牌错误: $e');
    }
  }

  /// 保存用户ID
  Future<void> saveUserId(String userId) async {
    try {
      await _storage.write(_keys.userId, userId);
    } catch (e) {
      debugPrint('保存用户ID错误: $e');
    }
  }

  /// 获取用户ID
  Future<String?> getUserId() async {
    try {
      return _storage.read<String>(_keys.userId);
    } catch (e) {
      debugPrint('获取用户ID错误: $e');
      return null;
    }
  }

  /// 移除用户ID
  Future<void> removeUserId() async {
    try {
      await _storage.remove(_keys.userId);
    } catch (e) {
      debugPrint('移除用户ID错误: $e');
    }
  }

  /// 保存语言代码
  Future<void> saveLanguageCode(String languageCode) async {
    try {
      await _storage.write(_keys.languageCode, languageCode);
    } catch (e) {
      debugPrint('保存语言代码错误: $e');
    }
  }

  /// 获取语言代码
  Future<String?> getLanguageCode() async {
    try {
      return _storage.read<String>(_keys.languageCode);
    } catch (e) {
      debugPrint('获取语言代码错误: $e');
      return null;
    }
  }

  /// 保存主题模式
  Future<void> saveThemeMode(String themeMode) async {
    try {
      await _storage.write(_keys.themeMode, themeMode);
    } catch (e) {
      debugPrint('保存主题模式错误: $e');
    }
  }

  /// 获取主题模式
  Future<String?> getThemeMode() async {
    try {
      return _storage.read<String>(_keys.themeMode);
    } catch (e) {
      debugPrint('获取主题模式错误: $e');
      return null;
    }
  }

  /// 保存是否第一次启动
  Future<void> saveFirstLaunch(bool isFirstLaunch) async {
    try {
      await _storage.write(_keys.isFirstLaunch, isFirstLaunch);
    } catch (e) {
      debugPrint('保存首次启动状态错误: $e');
    }
  }

  /// 获取是否第一次启动
  Future<bool> isFirstLaunch() async {
    try {
      return _storage.read<bool>(_keys.isFirstLaunch) ?? true;
    } catch (e) {
      debugPrint('获取首次启动状态错误: $e');
      return true;
    }
  }

  /// 清除所有数据
  Future<void> clearAll() async {
    try {
      await _storage.erase();
    } catch (e) {
      debugPrint('清除所有数据错误: $e');
    }
  }
}

/// 存储键名
class _StorageKeys {
  const _StorageKeys();

  /// 令牌
  final String token = 'token';

  /// 刷新令牌
  final String refreshToken = 'refresh_token';

  /// 用户ID
  final String userId = 'user_id';

  /// 语言代码
  final String languageCode = 'language_code';

  /// 主题模式
  final String themeMode = 'theme_mode';

  /// 是否首次启动
  final String isFirstLaunch = 'is_first_launch';
} 